AddCSLuaFile( "cl_init.lua" );
AddCSLuaFile( "shared.lua" );

include( "shared.lua" );

function ENT:Initialize()
	
	self:SetModel( self.Model );
	self:PhysicsInit( SOLID_VPHYSICS );
	self:SetMoveType( MOVETYPE_VPHYSICS );
	self:SetSolid( SOLID_VPHYSICS );
	
	local phys = self:GetPhysicsObject();
	if( phys and phys:IsValid() ) then
		
		phys:Wake();
		
	end
	
	C.ClearLinks( self );
	self.Contents = { };
	self.NextNetworkRefresh = 0;
	
	for k, v in pairs( self.Max ) do
		
		self:SetNWInt( "M" .. tostring( k ), v );
		
	end
	
	for k, v in pairs( self.Resources ) do
		
		self:SetNWInt( tostring( v ), 0 );
		self.Contents[v] = 0;
		
	end
	
end

function ENT:RefreshNetwork()
	
	for k, v in pairs( self.Resources ) do
		
		if( self:GetNWInt( tostring( v ) ) != self.Contents[v] ) then
			
			self:SetNWInt( tostring( v ), self.Contents[v] );
			
		end
		
	end
	
end

function ENT:CheckLinks()
	
	for k, v in pairs( self.Links ) do
		
		if( !v or !v:IsValid() ) then
			
			table.remove( self.Links, k );
			continue;
			
		end
		
		if( v:GetPos():Distance( self:GetPos() ) > 1024 ) then
			
			table.remove( self.Links, k );
			
			self:EmitSound( Sound( "weapons/stunstick/spark" .. tostring( math.random( 1, 3 ) ) .. ".wav" ) );
			
		end
		
	end
	
end

function ENT:GetMax( type )
	
	return self:GetNWInt( "M" .. tostring( type ) );
	
end

function ENT:GetAmount( type )
	
	return self.Contents[type] or 0;
	
end

function ENT:SetAmount( type, amt )
	
	self.Contents[type] = amt;
	
end

function ENT:AtMax( type )
	
	return ( self:GetAmount( type ) >= self:GetMax( type ) );
	
end

function ENT:AddResource( type, amt )
	
	if( table.HasValue( self.Resources, type ) ) then
		
		self:SetAmount( type, math.Clamp( self:GetAmount( type ) + amt, 0, self:GetMax( type ) ) );
		
	end
	
end

function ENT:RemoveResource( type, amt )
	
	if( table.HasValue( self.Resources, type ) ) then
		
		self:SetAmount( type, math.Clamp( self:GetAmount( type ) - amt, 0, self:GetMax( type ) ) );
		
	end
	
end

function ENT:Think()
	
	self:CheckLinks();
	self:RefreshNetwork();
	self:NextThink( CurTime() + 1 );
	return true;
	
end